package com.cybertron.ironhide.spider;

import java.util.concurrent.ExecutorService;

import com.cybertron.ironhide.spider.plugin.DoneException;
import com.cybertron.ironhide.spider.task.Task;

public class TaskExector implements Runnable {

	private final SpiderListener listener;

	private final ExecutorService pool;

	private final SiteManager siteManager;

	public TaskExector(ExecutorService pool, SiteManager siteManager,
			SpiderListener listener) {
		super();
		this.pool = pool;
		this.listener = listener;
		this.siteManager = siteManager;
	}

	@Override
	public void run() {
		while (true) {
			popTask();
		}
	}

	private void popTask() {
		try {
			Task task = siteManager.pollTask();
			if (task == null) {
				return;
			}
			Spider spider = new Spider(task, task.site, listener);
			pool.execute(spider);
		} catch (DoneException e) {
			listener.onInfo(Thread.currentThread(), null, e.toString());
			return;
		} catch (Exception e) {
			listener.onError(Thread.currentThread(), null, e.toString(), e);
		}

	}
}
